package stud.mpgame.network;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

/**
 * TCP реализация {@link NetworkMonitor}.
 *
 * @author f.pavel91@gmail.com
 * @version 1.4
 */
public class TCPNetworkMonitor extends NetworkMonitor {

    private TCPNetworkHandler tcpNetworkHandler;

    /**
     * Создание нового NetworkMonitor, работающего в TCP протоколе.
     *
     * @param startAppTime время старта сервера.
     * @param protocolVersion версия протокола передачи сообщений.
     */
    public TCPNetworkMonitor(long startAppTime, int protocolVersion) {
        super(startAppTime, protocolVersion);
        tcpNetworkHandler = new TCPNetworkHandler(this);
    }

    public final void bind() throws Exception {
        NioSocketAcceptor acceptor = new NioSocketAcceptor();
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();

        MdcInjectionFilter mdcInjectionFilter = new MdcInjectionFilter();
        chain.addLast("mdc", mdcInjectionFilter);

        chain.addLast("codec", new ProtocolCodecFilter(new TCPNetworkCodecFactory(startAppTime, protocolVersion, maxMessageBufferSize)));

        //addLogger(chain);

        acceptor.setHandler(tcpNetworkHandler);
        acceptor.bind(new InetSocketAddress(this.getPort()));

        System.out.println("Listening on port " + this.getPort());
    }

    private void addLogger(DefaultIoFilterChainBuilder chain) {
        chain.addLast("logger", new LoggingFilter());
        System.out.println("Logging ON");
    }

}
